package com.pr.makfilm.user.pages.room.create;

import com.google.common.collect.Table;
import com.pr.makfilm.core.ajax.ConfirmationCallListener;
import com.pr.makfilm.core.cmp.authorization.UserAuthorities;
import com.pr.makfilm.core.cmp.table.field.EnumDropDownField;
import com.pr.makfilm.domain.*;
import com.pr.makfilm.service.IRoomPlaceService;
import com.pr.makfilm.service.IRoomService;
import com.pr.makfilm.service.IRowHeaderService;
import com.pr.makfilm.user.api.UserApiKeys;
import com.pr.makfilm.user.api.UserApiMappings;
import com.pr.makfilm.user.navigation.NavigateToConstructRoomPage;
import com.pr.makfilm.user.navigation.NavigateToRoomDetailsPage;
import com.pr.makfilm.user.pages.AbstractUserPage;
import com.pr.makfilm.user.pages.room.create.preview.PreviewRowRepeater;
import com.pr.makfilm.user.pages.room.list.RoomListPage;
import com.pr.makfilm.user.utils.RoomPlaceUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.wicket.RestartResponseAtInterceptPageException;
import org.apache.wicket.ajax.AjaxRequestTarget;
import org.apache.wicket.ajax.attributes.AjaxRequestAttributes;
import org.apache.wicket.ajax.form.AjaxFormComponentUpdatingBehavior;
import org.apache.wicket.ajax.markup.html.AjaxLink;
import org.apache.wicket.authroles.authorization.strategies.role.annotations.AuthorizeInstantiation;
import org.apache.wicket.extensions.ajax.markup.html.IndicatingAjaxLink;
import org.apache.wicket.markup.html.WebMarkupContainer;
import org.apache.wicket.model.PropertyModel;
import org.apache.wicket.request.mapper.parameter.PageParameters;
import org.apache.wicket.spring.injection.annot.SpringBean;
import org.wicketstuff.annotation.mount.MountPath;

import java.util.ArrayList;
import java.util.List;

/**
 * Created with IntelliJ IDEA.
 * User: Pawel
 * Date: 09.10.13
 * Time: 17:29
 * To change this template use File | Settings | File Templates.
 */
@MountPath(UserApiMappings.CREATION_SUMMARY_ROOM_PAGE)
@AuthorizeInstantiation(UserAuthorities.USER)
public class SummaryRoomPage extends AbstractUserPage
{
   @SpringBean
   private IRoomService roomService;

   @SpringBean
   private IRowHeaderService rowHeaderService;

   @SpringBean
   private IRoomPlaceService roomPlaceService;

   private Room room;

   private Table<Integer, Integer, RoomPlace> placeTable;

   private WebMarkupContainer tableContainer;

   private List<String> xLabels = new ArrayList<String>();

   private List<String> yLabels = new ArrayList<String>();

   public SummaryRoomPage(final PageParameters parameters)
   {
      super(parameters);
      room = getRoom(parameters);
      List<RoomPlace> placeList = roomPlaceService.getByRoom(room);
      placeTable = RoomPlaceUtils.convertToTable(placeList);
   }

   @Override
   protected void onInitialize()
   {
      super.onInitialize();
      EnumDropDownField xStyle = new EnumDropDownField<NumberStyleEnum>("xStyle",
              new PropertyModel<NumberStyleEnum>(this, "room." + Room.FIELD_X_STYLE),
              NumberStyleEnum.values());
      xStyle.add(new AjaxFormComponentUpdatingBehavior("onchange")
      {
         @Override
         protected void onUpdate(AjaxRequestTarget target)
         {
            target.add(tableContainer);
         }
      });
      add(xStyle);

      EnumDropDownField xOrder = new EnumDropDownField<NumberOrderEnum>("xOrder",
              new PropertyModel<NumberOrderEnum>(this, "room." + Room.FIELD_X_ORDER),
              NumberOrderEnum.values());
      xOrder.add(new AjaxFormComponentUpdatingBehavior("onchange")
      {
         @Override
         protected void onUpdate(AjaxRequestTarget target)
         {
            target.add(tableContainer);
         }
      });
      add(xOrder);

      EnumDropDownField yStyle = new EnumDropDownField<NumberStyleEnum>("yStyle",
              new PropertyModel<NumberStyleEnum>(this, "room." + Room.FIELD_Y_STYLE),
              NumberStyleEnum.values());
      yStyle.add(new AjaxFormComponentUpdatingBehavior("onchange")
      {
         @Override
         protected void onUpdate(AjaxRequestTarget target)
         {
            target.add(tableContainer);
         }
      });
      add(yStyle);

      EnumDropDownField yOrder = new EnumDropDownField<NumberOrderEnum>("yOrder",
              new PropertyModel<NumberOrderEnum>(this, "room." + Room.FIELD_Y_ORDER),
              NumberOrderEnum.values());
      yOrder.add(new AjaxFormComponentUpdatingBehavior("onchange")
      {
         @Override
         protected void onUpdate(AjaxRequestTarget target)
         {
            target.add(tableContainer);
         }
      });
      add(yOrder);

      tableContainer = new WebMarkupContainer("table")
      {
         @Override
         protected void onConfigure()
         {
            RoomPlaceUtils.recalculatePlaceLabels(room, xLabels, yLabels, placeTable);
         }
      };
      tableContainer.setOutputMarkupPlaceholderTag(true);
      tableContainer.add(new PreviewRowRepeater("rows",
              new PropertyModel<Room>(this, "room"),
              new PropertyModel(this, "placeTable"),
              new PropertyModel(this, "yLabels")));
      add(tableContainer);
      add(new AjaxLink<Void>("back")
      {
         @Override
         public void onClick(AjaxRequestTarget target)
         {
            for (RoomPlace place : placeTable.values())
            {
               roomPlaceService.delete(place);
            }
            new NavigateToConstructRoomPage(room).navigate();
         }

         @Override
         protected void updateAjaxAttributes(AjaxRequestAttributes attributes)
         {
            super.updateAjaxAttributes(attributes);
            attributes.getAjaxCallListeners().add(new ConfirmationCallListener(getString("create.room.clean.confirm")));
         }
      });
      add(new IndicatingAjaxLink<Void>("submit")
      {
         @Override
         public void onClick(AjaxRequestTarget target)
         {
            room.setObjectState(ObjectStateEnum.ACTIVE);
            room = roomService.update(room);
            for (RoomPlace place : placeTable.values())
            {
               roomPlaceService.update(place);
            }
            for (int row = 0; row < yLabels.size(); row++)
            {
               rowHeaderService.createHeader(room, row, yLabels.get(row));
            }
            new NavigateToRoomDetailsPage(room).navigate();
         }
      });
   }

   private Room getRoom(PageParameters parameters)
   {
      String sid = parameters.get(UserApiKeys.SID_KEY).toString();
      if (StringUtils.isNotBlank(sid))
      {
         Room obj = roomService.getBySid(sid);
         if (obj == null || obj.getObjectState() != ObjectStateEnum.INACTIVE)
         {
            throw new RestartResponseAtInterceptPageException(RoomListPage.class);
         }
         return obj;
      }
      else
      {
         throw new RestartResponseAtInterceptPageException(RoomListPage.class);
      }
   }
}
